<template>
  <div class="model-evaluation">
    <div class="evaluation-content">
      <!-- 评估控制面板 -->
      <div class="control-panel">
        <h3 class="panel-title">
          <Icon type="md-analytics" size="20" />
          智能模型评估系统
        </h3>
        
        <div class="control-content">
          <p class="description">
            基于多维度指标对模型进行全面评估，包括综合评分、精度分析、效率对比、稳定性测试等。
          </p>
          
          <div class="control-actions">
            <div class="action-group">
              <!-- <label>评估模式:</label>
              <Select v-model="evaluationMode" style="width: 150px;" size="small">
                <Option value="current">当前模型</Option>
                <Option value="all">全部模型</Option>
                <Option value="compare">对比评估</Option>
                <Option value="trend">趋势分析</Option>
              </Select> -->
            </div>
            
            <div class="action-group">
              <!-- <label>评估维度:</label>
              <CheckboxGroup v-model="evaluationDimensions" size="small">
                <Checkbox label="accuracy">精度</Checkbox>
                <Checkbox label="efficiency">效率</Checkbox>
                <Checkbox label="stability">稳定性</Checkbox>
                <Checkbox label="robustness">鲁棒性</Checkbox>
              </CheckboxGroup> -->
            </div>
            
            <div class="action-group">
              <Button 
                type="primary" 
                @click="startEvaluation"
                icon="md-play"
                :loading="evaluating"
                size="small"
              >
                开始评估
              </Button>
              
              <!-- <Button 
                type="success" 
                @click="generateReport"
                icon="md-document"
                :loading="reportGenerating"
                size="small"  
              >
                生成报告
              </Button>
              
              <Button 
                type="info" 
                @click="loadTrends"
                icon="md-trending-up"
                :loading="trendsLoading"
                size="small"
              >
                趋势分析
              </Button> -->
            </div>
          </div>
        </div>
      </div>
      
      <!-- 模型总览仪表板 -->
      <div class="dashboard-overview" v-if="hasEvaluationData">
        <div class="overview-cards">
          <div class="overview-card best-model">
            <div class="card-header">
              <Icon type="md-trophy" size="24" />
              <h4>最佳模型</h4>
            </div>
            <div class="card-content">
              <div class="model-name">{{ bestModel.displayName }}</div>
              <div class="model-score">{{ formatAccuracy(bestModel.accuracy) }}</div>
              <div class="score-label">综合评分</div>
              <div class="model-metrics">
                <span>R²: {{ formatNumber(bestModel.metrics.r2) }}</span>
                <span>MAE: {{ formatNumber(bestModel.metrics.mae) }}</span>
              </div>
            </div>
          </div>
          
          <div class="overview-card total-models">
            <div class="card-header">
              <Icon type="md-apps" size="24" />
              <h4>评估模型</h4>
            </div>
            <div class="card-content">
              <div class="count">{{ totalModels }}</div>
              <div class="description">个模型参与评估</div>
            </div>
          </div>
          
          <div class="overview-card avg-accuracy">
            <div class="card-header">
              <Icon type="md-checkmark-circle" size="24" />
              <h4>平均综合评分</h4>
            </div>
            <div class="card-content">
              <div class="accuracy">{{ averageAccuracy > 0 ? formatNumber(averageAccuracy) + '%' : '暂无数据' }}</div>
          <div class="accuracy-label">平均综合评分</div>
              <div class="trend" :class="accuracyTrend">
                <Icon :type="accuracyTrend === 'up' ? 'md-trending-up' : 'md-trending-down'" />
                {{ accuracyTrend === 'up' ? '上升' : '下降' }}
              </div>
            </div>
          </div>
          
          <div class="overview-card evaluation-time">
            <div class="card-header">
              <Icon type="md-time" size="24" />
              <h4>评估耗时</h4>
            </div>
            <div class="card-content">
              <div class="time">{{ evaluationTime }}s</div>
              <div class="description">完成评估</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 模型排名与对比 -->
      <div class="model-ranking" v-if="hasEvaluationData">
        <div class="section-header">
          <h4>
            <Icon type="md-trophy" size="18" />
            模型综合排名
          </h4>
          <div class="ranking-controls">
            <Button 
              type="primary" 
              size="small" 
              @click="refreshRanking"
              icon="md-refresh"
            >
              刷新排名
            </Button>
          </div>
        </div>
        
        <div class="ranking-display">
          <!-- 前三名展示区 -->
          <div class="podium">
            <div 
              v-for="(model, index) in rankedModels.slice(0, 3)" 
              :key="model.name"
              class="podium-item"
              :class="['rank-' + (index + 1)]"
            >
              <div class="podium-rank">{{ index + 1 }}</div>
              <div class="podium-model">{{ model.displayName }}</div>
              <div class="podium-score">{{ formatAccuracy(model.accuracy) }}</div>
            <div class="score-label">综合评分</div>
              <div class="podium-metrics">
                <!-- <div>综合评分: {{ formatNumber(model.metrics.accuracy) }}%</div> -->
                <div>R²: {{ formatNumber(model.metrics.r2) }}</div>
                <div>MAE: {{ formatNumber(model.metrics.mae) }}</div>
                <div>RMSE: {{ formatNumber(model.metrics.rmse) }}</div>
                <div>MAPE: {{ formatNumber(model.metrics.mape) }}%</div>
                <div>最大误差: {{ formatNumber(model.metrics.max_error) }}</div>
              </div>
              <div class="podium-badge">
                <Icon 
                  :type="index === 0 ? 'md-medal' : index === 1 ? 'md-ribbon' : 'md-star'" 
                  size="24"
                />
              </div>
            </div>
          </div>
          
          <!-- 完整排名列表 -->
          <div class="ranking-list">
            <div 
              v-for="(model, index) in rankedModels" 
              :key="model.name"
              class="ranking-item"
              :class="{ 'top-performer': index < 3 }"
            >
              <div class="rank-info">
                <div class="rank-number">{{ index + 1 }}</div>
                <div class="model-info">
                  <div class="model-name">{{ model.displayName }}</div>
                  <div class="model-type">{{ getModelType(model.name) }}</div>
                </div>
              </div>
              
              <div class="metrics-summary">
                <div class="metric-item">
                  <span class="label">综合评分</span>
                  <span class="value">{{ formatNumber(model.metrics.accuracy) }}%</span>
                </div>
                <div class="metric-item">
                  <span class="label">训练日期</span>
                  <span class="value">{{ model.metrics.train_dt ? model.metrics.train_dt.slice(0, 10) : '未知' }}</span>
                </div>
                <div class="metric-item">
                  <span class="label">RMSE</span>
                  <span class="value">{{ formatNumber(model.metrics.rmse) }}</span>
                </div>
                <div class="metric-item">
                  <span class="label">MAPE</span>
                  <span class="value">{{ formatNumber(model.metrics.mape) }}%</span>
                </div>
                <div class="metric-item">
                  <span class="label">R²</span>
                  <span class="value">{{ formatNumber(model.metrics.r2) }}</span>
                </div>
                <div class="metric-item">
                  <span class="label">最大误差</span>
                  <span class="value">{{ formatNumber(model.metrics.max_error) }}</span>
                </div>
                <div class="metric-item">
                  <span class="label">MAE</span>
                  <span class="value">{{ formatNumber(model.metrics.mae) }}</span>
                </div>
              </div>
              
              <div class="score-display">
                <div class="score-bar">
                  <div class="score-fill" :style="{ width: model.accuracy + '%' }"></div>
                </div>
                                  <div class="score-text">{{ formatAccuracy(model.accuracy) }}</div>
            <div class="score-label">综合评分</div>
              </div>
              
              <div class="model-actions">
                <Button type="primary" size="small" @click="viewModelDetails(model)">
                  详情
                </Button>
                <!-- <Button type="info" size="small" @click="analyzeModel(model)">
                  分析
                </Button> -->
              </div>
            </div>
          </div>
        </div>
      </div>
      

      
      <!-- 性能趋势分析 -->
      <div class="trend-analysis" v-if="hasEvaluationData && evaluationMode === 'trend'">
        <div class="section-header">
          <h4>
            <Icon type="md-trending-up" size="18" />
            性能趋势分析
          </h4>
          <div class="trend-controls">
            <Select v-model="trendPeriod" style="width: 120px;" size="small" @on-change="updateTrends">
              <Option value="7">近7天</Option>
              <Option value="30">近30天</Option>
              <Option value="90">近90天</Option>
            </Select>
            <Select v-model="trendMetric" style="width: 100px;" size="small" @on-change="updateTrends">
              <Option value="mae">MAE</Option>
              <Option value="rmse">RMSE</Option>
              <Option value="r2">R²</Option>
            </Select>
          </div>
        </div>
        
        <div class="trend-content">
          <div id="trendChart" style="width: 100%; height: 400px;"></div>
        </div>
      </div>
      
      <!-- 样本分析 -->
      <!-- <div class="sample-analysis" v-if="hasEvaluationData">
        <div class="section-header">
          <h4>
            <Icon type="md-search" size="18" />
            样本分析
          </h4>
          <div class="sample-controls">
            <InputNumber 
              v-model="selectedSampleIndex" 
              :min="0" 
              :max="999" 
              style="width: 120px;"
              size="small"
              @on-change="loadSampleAnalysis"
            />
            <Button 
              type="primary" 
              size="small"
              @click="findBestSample"
              icon="md-checkmark"
            >
              最佳样本
            </Button>
            <Button 
              type="warning" 
              size="small"
              @click="findWorstSample"
              icon="md-warning"
            >
              最差样本
            </Button>
            <Button 
              type="info" 
              size="small"
              @click="randomSample"
              icon="md-shuffle"
            >
              随机样本
            </Button>
          </div>
        </div>
        
        <div class="sample-content" v-if="sampleData">
          <div class="sample-info">
            <div class="info-cards">
              <div class="info-card">
                <span class="label">样本编号</span>
                <span class="value">{{ sampleData.sample_index }}</span>
              </div>
              <div class="info-card">
                <span class="label">预测精度</span>
                <span class="value">{{ formatNumber(sampleData.metrics.accuracy) }}%</span>
              </div>
              <div class="info-card">
                <span class="label">MAE</span>
                <span class="value">{{ formatNumber(sampleData.metrics.mae) }}</span>
              </div>
              <div class="info-card">
                <span class="label">RMSE</span>
                <span class="value">{{ formatNumber(sampleData.metrics.rmse) }}</span>
              </div>
              <div class="info-card">
                <span class="label">MAPE</span>
                <span class="value">{{ formatNumber(sampleData.metrics.mape) }}%</span>
              </div>
              <div class="info-card">
                <span class="label">R²</span>
                <span class="value">{{ formatNumber(sampleData.metrics.r2) }}</span>
              </div>
            </div>
          </div>
          
          <div class="sample-chart">
            <div id="sampleChart" style="width: 100%; height: 200px;"></div>
          </div>
        </div>
      </div> -->
      
      <!-- 评估报告 -->
      <div class="evaluation-report" v-if="evaluationReport">
        <div class="section-header">
          <h4>
            <Icon type="md-document" size="18" />
            评估报告
          </h4>
          <div class="report-actions">
            <Button 
              type="success" 
              size="small"
              @click="exportReport"
              icon="md-download"
            >
              导出报告
            </Button>
            <Button 
              type="info" 
              size="small"
              @click="shareReport"
              icon="md-share"
            >
              分享报告
            </Button>
          </div>
        </div>
        
        <div class="report-content">
          <div class="report-summary">
            <h5>评估总结</h5>
            <div class="summary-grid">
              <div class="summary-item">
                <span class="label">评估时间</span>
                <span class="value">{{ formatDateTime(evaluationReport.timestamp) }}</span>
              </div>
              <div class="summary-item">
                <span class="label">参与模型</span>
                <span class="value">{{ evaluationReport.total_models }}个</span>
              </div>
              <div class="summary-item">
                <span class="label">最佳模型</span>
                <span class="value">{{ evaluationReport.best_model?.toUpperCase() }}</span>
              </div>
              <div class="summary-item">
                <span class="label">平均R²</span>
                <span class="value">{{ formatNumber(evaluationReport.evaluation_summary.avg_r2 * 100) }}%</span>
              </div>
              <div class="summary-item">
                <span class="label">平均综合评分</span>
                <span class="value">{{ getAverageAccuracy() !== null ? formatNumber(getAverageAccuracy()) + '%' : '暂无数据' }}</span>
              </div>
            </div>
          </div>
          
          <!-- <div class="report-recommendations">
            <h5>优化建议</h5>
            <ul>
              <li v-for="(recommendation, index) in getRecommendations()" :key="index">
                {{ recommendation }}
              </li>
            </ul>
          </div> -->
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="!hasEvaluationData && !evaluating" class="empty-state">
        <Icon type="md-analytics" size="64" />
        <h3>模型评估系统</h3>
        <p>点击"开始评估"对模型进行全面性能分析，包括综合评分、精度、R²等指标</p>
        <Button type="primary" size="large" @click="startEvaluation" icon="md-play">
          开始评估
        </Button>
      </div>
    </div>
  </div>
</template>

<script>
import { modelEvaluationAPI } from '@/utils/api'

export default {
  name: 'ModelEvaluation',
  data() {
    return {
      // 评估控制
      evaluationMode: 'all',
      evaluationDimensions: ['accuracy', 'efficiency'], // 评估维度
      evaluating: false,
      reportGenerating: false,
      trendsLoading: false,
      
      // 数据状态
      hasEvaluationData: false,
      evaluationData: null,
      evaluationReport: null,
      
      // 排名
      rankedModels: [],
      
      // 图表控制
      chartType: 'radar',
      
      // 趋势分析
      trendPeriod: '30',
      trendMetric: 'r2',
      trendData: null,
      
      // 样本分析 - 已禁用
      // selectedSampleIndex: 0,
      // sampleData: null,
      
      // 图表实例
      performanceChart: null,
      trendChart: null,
      // 样本分析图表已禁用
      // sampleChart: null,
      

    }
  },
  
  computed: {
    bestModel() {
      return this.rankedModels[0] || {}
    },
    
    totalModels() {
      return this.rankedModels.length
    },
    
    averageAccuracy() {
      const accuracy = this.getAverageAccuracy()
      return accuracy !== null ? accuracy : 0
    },
    
    accuracyTrend() {
      // 简单的趋势计算，实际应该基于历史数据
      return Math.random() > 0.5 ? 'up' : 'down'
    },
    
    evaluationTime() {
      return this.evaluationData ? (this.evaluationData.evaluation_time || 2.5) : 0
    },
    

  },
  
  mounted() {
    console.log('ModelEvaluation component mounted')
    this.initCharts()
    // Auto-start evaluation for demo purposes
    this.$nextTick(() => {
      this.startEvaluation()
    })
  },
  
  beforeDestroy() {
    this.disposeCharts()
  },
  
  methods: {
    async startEvaluation() {
      console.log('Starting model evaluation...')
      this.evaluating = true
      
      try {
        console.log('Fetching model evaluation data...')
        // 获取模型评估数据
        const [metricsResponse, rankingResponse, reportResponse] = await Promise.all([
          modelEvaluationAPI.getMetrics(),
          modelEvaluationAPI.getRanking(),
          modelEvaluationAPI.generateReport()
        ])
        
        console.log('API responses:', { metricsResponse, rankingResponse, reportResponse })
        
        // Extract data from axios responses (response interceptor already returns response.data)
        const metrics = metricsResponse
        const ranking = rankingResponse  
        const report = reportResponse
        
        console.log('Extracted API data:', { metrics, ranking, report })
        
        // 检查API响应是否成功
        const metricsSuccess = metrics && (metrics.success === true || metrics.status === 'success')
        const rankingSuccess = ranking && (ranking.success === true || ranking.status === 'success')
        const reportSuccess = report && (report.success === true || report.status === 'success')
        
        console.log('Success checks:', { metricsSuccess, rankingSuccess, reportSuccess })
        
        if (metricsSuccess && rankingSuccess && reportSuccess) {
          this.evaluationData = {
            metrics: metrics.data,
            ranking: ranking.data,
            comparison_data: await this.getComparisonData(),
            evaluation_time: 2.5
          }
          
          this.rankedModels = ranking.data
          this.evaluationReport = report.data
          this.hasEvaluationData = true
          
          // 调试：打印评估报告数据结构
          console.log('Evaluation report structure:', this.evaluationReport)
          console.log('Evaluation summary:', this.evaluationReport.evaluation_summary)
          console.log('Average accuracy:', this.evaluationReport.evaluation_summary.avg_accuracy)
          console.log('Average accuracy type:', typeof this.evaluationReport.evaluation_summary.avg_accuracy)
          console.log('Average accuracy formatted:', this.formatNumber(this.evaluationReport.evaluation_summary.avg_accuracy))
          
          console.log('Evaluation data loaded:', {
            hasData: this.hasEvaluationData,
            totalModels: this.rankedModels.length,
            bestModel: this.bestModel
          })
          
          // 更新图表
          this.updateAllCharts()
          
          this.$Message.success('模型评估完成')
        } else {
          console.error('API responses indicate errors:', { 
            metrics: { success: metrics?.success, status: metrics?.status, data: metrics?.data },
            ranking: { success: ranking?.success, status: ranking?.status, data: ranking?.data },
            report: { success: report?.success, status: report?.status, data: report?.data }
          })
          this.$Message.error('评估数据获取失败')
        }
      } catch (error) {
        console.error('评估失败:', error)
        this.$Message.error('评估失败: ' + error.message)
      } finally {
        this.evaluating = false
      }
    },
    
    async getComparisonData() {
      try {
        const response = await modelEvaluationAPI.getComparison()
        return response.success ? response.data : []
      } catch (error) {
        console.error('获取对比数据失败:', error)
        return []
      }
    },
    
    async generateReport() {
      this.reportGenerating = true
      
      try {
        const response = await modelEvaluationAPI.generateReport()
        if (response.success) {
          this.evaluationReport = response.data
          this.$Message.success('报告生成成功')
        }
      } catch (error) {
        console.error('生成报告失败:', error)
        this.$Message.error('生成报告失败')
      } finally {
        this.reportGenerating = false
      }
    },
    
    async loadTrends() {
      this.trendsLoading = true
      
      try {
        const response = await modelEvaluationAPI.getPerformanceTrends()
        if (response.success) {
          this.trendData = response.data
          this.updateTrendChart()
          this.$Message.success('趋势数据加载成功')
        }
      } catch (error) {
        console.error('加载趋势数据失败:', error)
        this.$Message.error('加载趋势数据失败')
      } finally {
        this.trendsLoading = false
      }
    },
    
    async updateRanking() {
      try {
        const response = await modelEvaluationAPI.getRanking()
        if (response.success) {
          this.rankedModels = response.data
          this.updateAllCharts()
        }
      } catch (error) {
        console.error('更新排名失败:', error)
      }
    },
    
    // 样本分析方法 - 已禁用
    // async loadSampleAnalysis() {
    //   try {
    //     const response = await modelEvaluationAPI.getSampleDetails(this.selectedSampleIndex)
    //     if (response.success) {
    //       this.sampleData = response.data
    //       this.updateSampleChart()
    //     }
    //   } catch (error) {
    //     console.error('加载样本分析失败:', error)
    //     this.$Message.error('加载样本分析失败')
    //   }
    // },
    
    // async findBestSample() {
    //   // 查找最佳样本
    //   this.selectedSampleIndex = 0
    //   await this.loadSampleAnalysis()
    // },
    
    // async findWorstSample() {
    //   // 查找最差样本
    //   this.selectedSampleIndex = 100
    //   await this.loadSampleAnalysis()
    // },
    
    // randomSample() {
    //   this.selectedSampleIndex = Math.floor(Math.random() * 1000)
    //   this.loadSampleAnalysis()
    // },
    
    initCharts() {
      this.$nextTick(() => {
        const elements = [
          { id: 'performanceChart', chart: 'performanceChart' },
          { id: 'trendChart', chart: 'trendChart' }
          // 样本分析图表已禁用
          // { id: 'sampleChart', chart: 'sampleChart' }
        ]
        
        elements.forEach(({ id, chart }) => {
          const el = document.getElementById(id)
          if (el && window.echarts) {
            this[chart] = window.echarts.init(el)
          }
        })
      })
    },
    
    disposeCharts() {
      const charts = ['performanceChart', 'trendChart']
      // 样本分析图表已禁用
      // const charts = ['performanceChart', 'trendChart', 'sampleChart']
      charts.forEach(chart => {
        if (this[chart]) {
          this[chart].dispose()
          this[chart] = null
        }
      })
    },
    
    updateAllCharts() {
      this.$nextTick(() => {
        this.updatePerformanceChart()
        if (this.trendData) {
          this.updateTrendChart()
        }
        // 样本分析图表已禁用
        // if (this.sampleData) {
        //   this.updateSampleChart()
        // }
      })
    },
    
    updatePerformanceChart() {
      if (!this.performanceChart || !this.rankedModels.length) return
      
      const models = this.rankedModels.map(m => m.displayName)
      
      if (this.chartType === 'radar') {
        this.updateRadarChart(models)
      } else if (this.chartType === 'bar') {
        this.updateBarChart(models)
      } else if (this.chartType === 'heatmap') {
        this.updateHeatmapChart(models)
      }
    },
    
    updateRadarChart(models) {
      const radarData = this.rankedModels.map(model => ({
        name: model.displayName,
        value: [
          model.accuracy,
          model.metrics.r2 * 100,
          (1 - model.metrics.mae) * 100,
          (1 - model.metrics.rmse) * 100,
          (1 - model.metrics.training_time / 10) * 100
        ]
      }))
      
      const option = {
        title: { text: '模型性能雷达图', left: 'center', textStyle: { color: '#f7dc6f' } },
        tooltip: { trigger: 'item' },
        legend: { data: models, bottom: 10, textStyle: { color: '#f7dc6f' } },
        radar: {
          indicator: [
            { name: '精度', max: 100 },
            { name: 'R²', max: 100 },
            { name: 'MAE', max: 100 },
            { name: 'RMSE', max: 100 },
            { name: '效率', max: 100 }
          ],
          axisLabel: { color: '#999' },
          splitLine: { lineStyle: { color: '#333' } }
        },
        series: [{
          type: 'radar',
          data: radarData
        }]
      }
      
      this.performanceChart.setOption(option)
    },
    
    updateBarChart(models) {
      const option = {
        title: { text: '模型性能对比', left: 'center', textStyle: { color: '#f7dc6f' } },
        tooltip: { trigger: 'axis' },
        legend: { data: ['精度', 'R²', 'MAE', 'RMSE'], bottom: 10, textStyle: { color: '#f7dc6f' } },
        xAxis: { type: 'category', data: models, axisLabel: { color: '#999' } },
        yAxis: { type: 'value', axisLabel: { color: '#999' } },
        series: [
          {
            name: '精度',
            type: 'bar',
            data: this.rankedModels.map(m => m.accuracy)
          },
          {
            name: 'R²',
            type: 'bar',
            data: this.rankedModels.map(m => m.metrics.r2)
          },
          {
            name: 'MAE',
            type: 'bar',
            data: this.rankedModels.map(m => m.metrics.mae)
          },
          {
            name: 'RMSE',
            type: 'bar',
            data: this.rankedModels.map(m => m.metrics.rmse)
          }
        ]
      }
      
      this.performanceChart.setOption(option)
    },
    
    updateHeatmapChart(models) {
      const metrics = ['accuracy', 'r2', 'mae', 'rmse']
      const data = []
      
      models.forEach((model, modelIndex) => {
        metrics.forEach((metric, metricIndex) => {
          const value = this.rankedModels[modelIndex].metrics[metric]
          data.push([modelIndex, metricIndex, value])
        })
      })
      
      const option = {
        title: { text: '模型性能热力图', left: 'center', textStyle: { color: '#f7dc6f' } },
        tooltip: {
          position: 'top',
          formatter: function(params) {
            return `${models[params.data[0]]}<br/>${metrics[params.data[1]].toUpperCase()}: ${params.data[2].toFixed(4)}`
          }
        },
        xAxis: {
          type: 'category',
          data: models,
          axisLabel: { color: '#999' }
        },
        yAxis: {
          type: 'category',
          data: metrics.map(m => m.toUpperCase()),
          axisLabel: { color: '#999' }
        },
        visualMap: {
          min: 0,
          max: 1,
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '5%',
          textStyle: { color: '#f7dc6f' }
        },
        series: [{
          type: 'heatmap',
          data: data,
          label: {
            show: true,
            formatter: function(params) {
              return params.data[2].toFixed(3)
            }
          }
        }]
      }
      
      this.performanceChart.setOption(option)
    },
    
    updateTrendChart() {
      if (!this.trendChart || !this.trendData) return
      
      const option = {
        title: { text: '性能趋势分析', left: 'center', textStyle: { color: '#f7dc6f' } },
        tooltip: { trigger: 'axis' },
        legend: { 
          data: Object.keys(this.trendData.metrics), 
          bottom: 10, 
          textStyle: { color: '#f7dc6f' } 
        },
        xAxis: {
          type: 'category',
          data: this.trendData.dates,
          axisLabel: { color: '#999' }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#999' }
        },
        series: Object.entries(this.trendData.metrics).map(([model, data]) => ({
          name: model.toUpperCase(),
          type: 'line',
          data: data[this.trendMetric],
          smooth: true
        }))
      }
      
      this.trendChart.setOption(option)
    },
    
    // 样本分析图表更新方法 - 已禁用
    // updateSampleChart() {
    //   if (!this.sampleChart || !this.sampleData) return
    //   
    //   const timeLabels = Array.from({length: 96}, (_, i) => {
    //     const hour = Math.floor(i / 4)
    //     const minute = (i % 4) * 15
    //     return `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
    //   })
    //   
    //   const option = {
    //     title: { text: `样本 ${this.sampleData.sample_index} 预测分析`, textStyle: { color: '#f7dc6f' } },
    //     tooltip: { trigger: 'axis' },
    //     legend: { data: ['真实值', '预测值', '误差'], textStyle: { color: '#f7dc6f' } },
    //     xAxis: {
    //       type: 'category',
    //       data: timeLabels,
    //       axisLabel: { color: '#999', interval: 11 }
    //     },
    //     yAxis: [
    //       {
    //       type: 'value',
    //         name: '负荷值',
    //         axisLabel: { color: '#999' }
    //       },
    //       {
    //         type: 'value',
    //         name: '误差',
    //         position: 'right',
    //         axisLabel: { color: '#999' }
    //       }
    //     ],
    //     series: [
    //       {
    //         name: '真实值',
    //         type: 'line',
    //         data: this.sampleData.true_values,
    //         itemStyle: { color: '#00d4aa' },
    //         smooth: true
    //       },
    //       {
    //         name: '预测值',
    //         type: 'line',
    //         data: this.sampleData.predicted_values,
    //         itemStyle: { color: '#f7dc6f' },
    //         smooth: true
    //       },
    //       {
    //         name: '误差',
    //         type: 'line',
    //         yAxisIndex: 1,
    //         data: this.sampleData.errors,
    //         itemStyle: { color: '#ff6b6b' },
    //         smooth: true
    //       }
    //     ]
    //   }
    //   
    //   this.sampleChart.setOption(option)
    // },
    
    refreshRanking() {
      this.updateRanking()
    },
    

    
    updateTrends() {
      this.loadTrends()
    },
    
    viewModelDetails(model) {
      this.$Modal.info({
        title: `${model.displayName} 详细信息`,
        content: `
          <div>
                                            <p><strong>精度:</strong> ${this.formatAccuracy(model.accuracy)}</p>
            <p><strong>R²:</strong> ${this.formatNumber(model.metrics.r2)}</p>
            <p><strong>MAE:</strong> ${this.formatNumber(model.metrics.mae)}</p>
            <p><strong>RMSE:</strong> ${this.formatNumber(model.metrics.rmse)}</p>
            <p><strong>训练时间:</strong> ${this.formatNumber(model.metrics.training_time)}s</p>
            <p><strong>模型大小:</strong> ${this.formatNumber(model.metrics.model_size)}MB</p>
          </div>
        `,
        width: 500
      })
    },
    
    analyzeModel(model) {
      this.$Message.info(`正在分析模型: ${model.displayName}`)
      // 可以跳转到详细分析页面
    },
    

    
    exportReport() {
      try {
        const reportData = JSON.stringify(this.evaluationReport, null, 2)
        this.downloadFile(reportData, '模型评估报告.json', 'application/json')
        this.$Message.success('报告导出成功')
      } catch (error) {
        this.$Message.error('报告导出失败')
      }
    },
    
    shareReport() {
      this.$Message.info('分享功能待实现')
    },
    
    convertToCSV(data) {
      if (!data.length) return ''
      
      const headers = Object.keys(data[0])
      const csvContent = [
        headers.join(','),
        ...data.map(row => headers.map(header => row[header]).join(','))
      ].join('\n')
      
      return csvContent
    },
    
    downloadCSV(csv, filename) {
      const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = filename
      link.click()
    },
    
    downloadFile(content, filename, type) {
      const blob = new Blob([content], { type })
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = filename
      link.click()
    },
    
    getModelType(modelName) {
      const types = {
        'lightgbm': '梯度提升',
        'xgboost': '极端梯度提升',
        'mlp': '多层感知机',
        'ensemble': '集成学习'
      }
      return types[modelName.toLowerCase()] || '未知类型'
    },
    
    getScoreColor(score) {
      if (score >= 80) return '#00d4aa'
      if (score >= 60) return '#f7dc6f'
      if (score >= 40) return '#feca57'
      return '#ff6b6b'
    },
    
    getRecommendations() {
      if (!this.evaluationReport) return []
      
      const recommendations = []
      const avgR2 = this.evaluationReport.evaluation_summary.avg_r2
      const variance = this.evaluationReport.evaluation_summary.performance_variance
      
      if (avgR2 < 0.6) {
        recommendations.push('整体模型精度较低，建议优化特征工程和数据预处理')
      }
      
      if (variance > 0.01) {
        recommendations.push('模型性能差异较大，建议采用集成学习方法')
      }
      
      if (this.evaluationReport.evaluation_summary.avg_training_time > 5) {
        recommendations.push('训练时间较长，建议考虑模型压缩或优化算法')
      }
      
      if (recommendations.length === 0) {
        recommendations.push('模型性能良好，建议持续监控和优化')
      }
      
      return recommendations
    },
    
    formatNumber(value) {
      if (typeof value !== 'number') return value
      if (value === 0) return '0'
      if (Math.abs(value) >= 1) return value.toFixed(3)
      return value.toFixed(6)
    },
    
    formatScore(score) {
      return (score * 100).toFixed(1) + '%'
    },
    
    formatAccuracy(accuracy) {
      return accuracy.toFixed(1) + '%'
    },
    
    formatDateTime(timestamp) {
      return new Date(timestamp).toLocaleString('zh-CN')
    },
    
    getAverageAccuracy() {
      // 优先使用评估报告中的平均精度
      if (this.evaluationReport?.evaluation_summary?.avg_accuracy !== undefined) {
        console.log('Using evaluation report avg_accuracy:', this.evaluationReport.evaluation_summary.avg_accuracy)
        return this.evaluationReport.evaluation_summary.avg_accuracy
      }
      
      // 如果没有，从排名模型中计算
      if (this.rankedModels && this.rankedModels.length > 0) {
        const avg = this.rankedModels.reduce((sum, model) => sum + (model.metrics.accuracy || 0), 0) / this.rankedModels.length
        console.log('Calculated avg_accuracy from ranked models:', avg)
        return avg
      }
      
      // 没有数据时返回null
      console.log('No accuracy data available')
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.model-evaluation {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #0c1426 0%, #1a2332 50%, #0f1b2a 100%);
  padding: 20px;
  box-sizing: border-box;
  
  .evaluation-content {
    display: flex;
    flex-direction: column;
    gap: 25px;
    
    // 控制面板
    .control-panel {
      background: rgba(7, 19, 50, 0.9);
      border: 1px solid #1a3c58;
      border-radius: 12px;
      padding: 20px;
      backdrop-filter: blur(10px);
      
      .panel-title {
        color: #f7dc6f;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #1a3c58;
        display: flex;
        align-items: center;
        gap: 10px;
      }
      
      .control-content {
        .description {
          color: #ddd;
          font-size: 14px;
          line-height: 1.6;
          margin-bottom: 20px;
        }
        
        .control-actions {
          display: flex;
          align-items: flex-end;
          gap: 25px;
          flex-wrap: wrap;
          
          .action-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
            
            label {
              color: #f7dc6f;
              font-size: 13px;
              font-weight: 500;
            }
          }
        }
      }
    }
    
    // 总览仪表板
    .dashboard-overview {
      .overview-cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
        
        .overview-card {
          background: rgba(7, 19, 50, 0.8);
          border: 1px solid #1a3c58;
          border-radius: 12px;
          padding: 20px;
          backdrop-filter: blur(10px);
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
          }
          
          .card-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
            
            h4 {
              color: #f7dc6f;
              margin: 0;
              font-size: 16px;
            }
            
            :deep(.ivu-icon) {
              color: #f7dc6f;
            }
          }
          
          .card-content {
            .model-name {
              font-size: 24px;
              font-weight: bold;
              color: #00d4aa;
              margin-bottom: 8px;
            }
            
            .model-score {
              font-size: 20px;
              color: #f7dc6f;
              margin-bottom: 5px;
            }
            
            .score-label {
              font-size: 12px;
              color: #999;
              text-align: left;
              margin-bottom: 10px;
            }
            
            .model-metrics {
              display: flex;
              gap: 15px;
              font-size: 12px;
              color: #999;
            }
            
            .count {
              font-size: 32px;
              font-weight: bold;
              color: #f7dc6f;
            }
            
            .accuracy {
              font-size: 28px;
              font-weight: bold;
              color: #00d4aa;
            }
            
            .accuracy-label {
              font-size: 12px;
              color: #999;
              text-align: left;
              margin-top: 5px;
            }
            
            .time {
              font-size: 28px;
              font-weight: bold;
              color: #4ecdc4;
            }
            
            .description {
              color: #999;
              font-size: 14px;
            }
            
            .trend {
              display: flex;
              align-items: center;
              gap: 5px;
              font-size: 12px;
              
              &.up {
                color: #00d4aa;
              }
              
              &.down {
                color: #ff6b6b;
              }
            }
          }
        }
      }
    }
    
    // 模型排名
    .model-ranking {
      background: rgba(7, 19, 50, 0.8);
      border: 1px solid #1a3c58;
      border-radius: 12px;
      padding: 20px;
      backdrop-filter: blur(10px);
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 25px;
        padding-bottom: 15px;
        border-bottom: 1px solid #1a3c58;
        
        h4 {
          color: #f7dc6f;
          font-size: 16px;
          font-weight: bold;
          margin: 0;
          display: flex;
          align-items: center;
          gap: 8px;
        }
        
        .ranking-controls {
          display: flex;
          align-items: center;
        }
      }
      
      .ranking-display {
        .podium {
          display: flex;
          justify-content: center;
          align-items: flex-end;
          gap: 20px;
          margin-bottom: 30px;
          
          .podium-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;
            padding: 20px 15px;
            border-radius: 12px;
            position: relative;
            min-width: 140px;
            
            &.rank-1 {
              background: linear-gradient(135deg, #ffd700, #ffb300);
              color: #000;
              order: 2;
              min-height: 320px;
              height: auto;
            }
            
            &.rank-2 {
              background: linear-gradient(135deg, #c0c0c0, #a0a0a0);
              color: #000;
              order: 1;
              min-height: 320px;
              height: auto;
            }
            
            &.rank-3 {
              background: linear-gradient(135deg, #cd7f32, #b8860b);
              color: #000;
              order: 3;
              min-height: 320px;
              height: auto;
            }
            
            .podium-rank {
              font-size: 28px;
              font-weight: bold;
              margin-bottom: 10px;
            }
            
            .podium-model {
              font-size: 18px;
              font-weight: bold;
              margin-bottom: 10px;
            }
            
            .podium-score {
              font-size: 16px;
              margin-bottom: 10px;
            }
            
            .podium-metrics {
              font-size: 11px;
              text-align: center;
              line-height: 1.3;
              margin-bottom: 10px;
              flex: 1;
              display: flex;
              flex-direction: column;
              justify-content: center;
            }
            
            .podium-badge {
              font-size: 28px;
              color: #ff6b6b;
            }
          }
        }
        
        .ranking-list {
          .ranking-item {
            display: flex;
            align-items: center;
            padding: 20px;
            margin-bottom: 15px;
            background: rgba(26, 60, 88, 0.3);
            border-radius: 12px;
            border: 1px solid #1a3c58;
            transition: all 0.3s ease;
            
            &:hover {
              background: rgba(247, 220, 111, 0.1);
              border-color: #f7dc6f;
            }
            
            &.top-performer {
              border-color: #f7dc6f;
              background: rgba(247, 220, 111, 0.05);
            }
            
            .rank-info {
              display: flex;
              align-items: center;
              gap: 20px;
              min-width: 200px;
              
              .rank-number {
                font-size: 24px;
                font-weight: bold;
                color: #f7dc6f;
                min-width: 40px;
                text-align: center;
              }
              
              .model-info {
                .model-name {
                  font-size: 18px;
                  font-weight: bold;
                  color: #f7dc6f;
                  margin-bottom: 5px;
                }
                
                .model-type {
                  font-size: 12px;
                  color: #999;
                }
              }
            }
            
            .metrics-summary {
              flex: 1;
              display: flex;
              gap: 30px;
              
              .metric-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 5px;
                
                .label {
                  font-size: 12px;
                  color: #999;
                }
                
                .value {
                  font-size: 16px;
                  font-weight: bold;
                  color: #f7dc6f;
                }
              }
            }
            
            .score-display {
              display: flex;
              flex-direction: column;
              align-items: center;
              gap: 10px;
              min-width: 150px;
              
              .score-bar {
                width: 100%;
                height: 20px;
                background: rgba(7, 19, 50, 0.5);
                border-radius: 10px;
                overflow: hidden;
                position: relative;
                
                .score-fill {
                  height: 100%;
                  background: linear-gradient(90deg, #f7dc6f, #f39c12);
                  border-radius: 10px;
                  transition: width 0.8s ease;
                }
              }
              
              .score-text {
                font-size: 16px;
                font-weight: bold;
                color: #f7dc6f;
              }
              
              .score-label {
                font-size: 10px;
                color: #999;
                text-align: left;
                margin-top: 2px;
              }
            }
            
            .model-actions {
              display: flex;
              gap: 10px;
            }
          }
        }
      }
    }
    

    
    // 趋势分析
    .trend-analysis {
      background: rgba(7, 19, 50, 0.8);
      border: 1px solid #1a3c58;
      border-radius: 12px;
      padding: 20px;
      backdrop-filter: blur(10px);
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #1a3c58;
        
        h4 {
          color: #f7dc6f;
          font-size: 16px;
          font-weight: bold;
          margin: 0;
          display: flex;
          align-items: center;
          gap: 8px;
        }
        
        .trend-controls {
          display: flex;
          gap: 10px;
        }
      }
    }
    
    
    // 评估报告
    .evaluation-report {
      background: rgba(7, 19, 50, 0.8);
      border: 1px solid #1a3c58;
      border-radius: 12px;
      padding: 20px;
      backdrop-filter: blur(10px);
      
      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #1a3c58;
        
        h4 {
          color: #f7dc6f;
          font-size: 16px;
          font-weight: bold;
          margin: 0;
          display: flex;
          align-items: center;
          gap: 8px;
        }
        
        .report-actions {
          display: flex;
          gap: 10px;
        }
      }
      
      .report-content {
        .report-summary {
          margin-bottom: 25px;
          
          h5 {
            color: #00d4aa;
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 15px;
          }
          
          .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            
            .summary-item {
              background: rgba(26, 60, 88, 0.3);
              border-radius: 8px;
              padding: 15px;
              
              .label {
                display: block;
                font-size: 12px;
                color: #999;
                margin-bottom: 5px;
              }
              
              .value {
                font-size: 16px;
                font-weight: bold;
                color: #f7dc6f;
              }
            }
          }
        }
        
        .report-recommendations {
          h5 {
            color: #00d4aa;
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 15px;
          }
          
          ul {
            list-style: none;
            padding: 0;
            
            li {
              color: #ddd;
              line-height: 1.6;
              margin-bottom: 10px;
              padding-left: 20px;
              position: relative;
              
              &::before {
                content: '•';
                color: #f7dc6f;
                position: absolute;
                left: 0;
                font-weight: bold;
              }
            }
          }
        }
      }
    }
    
    // 样本分析 - 已禁用
    // .sample-analysis {
    //   background: rgba(7, 19, 50, 0.8);
    //   border: 1px solid #1a3c58;
    //   border-radius: 12px;
    //   padding: 15px;
    //   backdrop-filter: blur(10px);
    //   
    //   .section-header {
    //     display: flex;
    //     justify-content: space-between;
    //     align-items: center;
    //     margin-bottom: 20px;
    //     padding-bottom: 15px;
    //     border-bottom: 1px solid #1a3c58;
    //     
    //   h4 {
    //       color: #f7dc6f;
    //       font-size: 16px;
    //       font-weight: bold;
    //       margin: 0;
    //       display: flex;
    //       align-items: center;
    //       gap: 8px;
    //     }
    //     
    //     .sample-controls {
    //       display: flex;
    //       align-items: center;
    //       gap: 10px;
    //     }
    //   }
    //   
    //   .sample-content {
    //     .sample-info {
    //       margin-bottom: 15px;
    //       
    //       .info-cards {
    //         display: grid;
    //         grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
    //         gap: 10px;
    //         
    //         .info-card {
    //           background: rgba(26, 60, 88, 0.3);
    //           border-radius: 8px;
    //           padding: 10px;
    //           text-align: center;
    //           
    //           .label {
    //             display: block;
    //             font-size: 11px;
    //             color: #999;
    //             margin-bottom: 3px;
    //           }
    //           
    //           .value {
    //             font-size: 14px;
    //             font-weight: bold;
    //             color: #f7dc6f;
    //           }
    //         }
    //       }
    //     }
    //   }
    // }

    // .sample-chart {
    //   #sampleChart {
    //     height: 60px !important; // 再减小
    //   }
    // }
    
    // 空状态
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 100px 20px;
      text-align: center;
      background: rgba(7, 19, 50, 0.5);
      border: 1px dashed #1a3c58;
      border-radius: 12px;
      
      :deep(.ivu-icon) {
        color: #f7dc6f;
        margin-bottom: 20px;
        opacity: 0.7;
      }
      
      h3 {
        color: #f7dc6f;
        font-size: 24px;
        margin-bottom: 15px;
      }
      
      p {
        color: #999;
        font-size: 16px;
        margin-bottom: 30px;
      }
    }
  }
}

// 按钮样式
:deep(.ivu-btn) {
  &.ivu-btn-primary {
    background: linear-gradient(135deg, #f7dc6f, #f39c12);
    border-color: #f7dc6f;
    color: #000;
    
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 15px rgba(247, 220, 111, 0.4);
    }
  }
  
  &.ivu-btn-success {
    background: linear-gradient(135deg, #26de81, #20bf68);
    border-color: #26de81;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 15px rgba(38, 222, 129, 0.4);
    }
  }
  
  &.ivu-btn-info {
    background: linear-gradient(135deg, #4ecdc4, #44a08d);
    border-color: #4ecdc4;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 15px rgba(78, 205, 196, 0.4);
    }
  }
  
  &.ivu-btn-warning {
    background: linear-gradient(135deg, #feca57, #ff9500);
    border-color: #feca57;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 15px rgba(254, 202, 87, 0.4);
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .model-evaluation {
    .evaluation-content {
      .dashboard-overview .overview-cards {
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
      }
      
      .model-ranking .ranking-display .podium {
        gap: 15px;
        
        .podium-item {
          min-width: 120px;
          padding: 15px;
          min-height: 300px;
          height: auto;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .model-evaluation {
    padding: 15px;
    
    .evaluation-content {
      gap: 20px;
      
      .control-panel {
        padding: 15px;
        
        .control-content .control-actions {
          flex-direction: column;
          align-items: stretch;
          gap: 15px;
        }
      }
      
      .dashboard-overview .overview-cards {
        grid-template-columns: 1fr;
      }
      
      .model-ranking {
        .ranking-display {
          .podium {
            flex-direction: column;
            align-items: center;
            
            .podium-item {
              width: 100%;
              min-height: 280px !important;
              height: auto !important;
              order: initial !important;
            }
          }
          
          .ranking-list .ranking-item {
            flex-direction: column;
            gap: 15px;
            
            .metrics-summary {
              flex-direction: column;
              gap: 10px;
            }
          }
        }
      }
    }
  }
}
</style>